<template>
  <div>
    <el-form @submit.native.prevent class="query-table-form" :inline="true" :model="params">
      <el-form-item label="所属区域">
        <select-address
          v-model="params.address_code"
          :auto-top="true"
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="request">确认选择</el-button>
      </el-form-item>
    </el-form>
    <c-table
      border
      v-loading="loading"
      class="table-sm"
      :columns="tableColumns"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>

      <template v-slot:status="scope">
        <div
          class="badge"
          :class="`badge-${scope.row.statusStyle}`"
          :title="scope.row.pre_approval_des || ''"
        >
          {{ scope.row.statusLabel }}
        </div>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <el-dialog
      append-to-body
      title="受理信息"
      top="50px"
      :before-close="beforeClose"
      width="50%"
      :close-on-click-modal="false"
      :visible.sync="prelimVisiable"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="是否联保">
          <el-radio v-model="form.gua_type" :label="0">否</el-radio>
          <el-radio v-model="form.gua_type" :label="1">是</el-radio>
        </el-form-item>
        <el-form-item label="主办银行" prop="publicBank">
          <select-banks
            v-model="form.publicBank"
            class="form-control-ml"
            @select="setBank"
          ></select-banks>
        </el-form-item>
        <el-form-item label="A角" prop="res_a">
          <select-staff
            v-model="form.res_a"
            class="form-control-ml"
            placeholder="请选择A角"
          ></select-staff>
        </el-form-item>
        <el-form-item label="B角" prop="res_b">
          <select-staff
            v-model="form.res_b"
            class="form-control-ml"
            placeholder="请选择B角"
          ></select-staff>
        </el-form-item>
        <el-form-item>
          <el-button :loading="approvalLoading" type="primary" @click="submitForm">
            确认受理
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { enumOrgClass } from '@/credit/plugins/enum'
import SelectStaff from '@/components/select/SelectStaff'
import SelectBanks from '@/credit/components/select/SelectBanks'
import { mapGetters } from 'vuex'
import { enumPreApproval } from '@/gov/plugins/enum'
import SelectAddress from '@/components/select/SelectAddress'
const enumStatusStyle = {
  0: 'info',
  1: 'success',
  2: 'danger',
}
export default {
  components: {
    SelectBanks,
    SelectAddress,
    SelectStaff,
  },
  props: {},
  data() {
    return {
      loading: false,
      params: {
        index: 1,
        size: 20,
        'submit_type.in': '1,2',
        'recommend_status.eq': 1,
        'is_approval.eq': 0,
        'bank_id.is': 'null',
      },
      tableName: 'customer_related_view',
      tableColumns: [
        { attrs: { label: '选择', type: 'selection', align: 'center' } },
        {
          attrs: { label: '主体名称', prop: 'customer_name', minWidth: '110px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '地址', prop: 'address' }, slot: 'address' },
        {
          attrs: { label: '组织形式', prop: 'org_class', align: 'center' },
          process: v => enumOrgClass[v] || '-',
        },
        { attrs: { label: '客户来源', prop: 'submit_person_name', align: 'center' } },
        { attrs: { label: '推荐银行', prop: 'bank_name', align: 'center' } },
        { attrs: { label: '贷款年限', prop: 'load_years', align: 'center' } },
        { attrs: { label: '项目状态', prop: 'statusLabel', align: 'center' }, slot: 'status' },
      ],
      tableData: [],
      form: {
        publicBank: [],
        res_a: '',
        res_b: '',
        gua_type: 1,
      },
      rules: {
        publicBank: [
          { required: true, message: '请选择发布银行', trigger: 'change' },
          { required: true, message: '请选择发布银行', trigger: 'blur' },
        ],
        res_a: [{ required: true, message: '请选择A角', trigger: 'change' }],
        res_b: [{ required: true, message: '请选择B角', trigger: 'change' }],
      },
      totalCount: 0,
      selectData: [],
      approvalLoading: false,
      prelimVisiable: false,
    }
  },
  computed: {
    isManager() {
      return ['org_credit_super', 'org_c_manage', 'org_r_emp', 'org_r_manage', 'org_corp'].includes(
        this.job
      )
    },
    isUserTown() {
      return this.user.orgRegionLever === 3
    },
    ...mapGetters(['user', 'userId', 'clientId', 'job']),
  },
  watch: {},
  created() {
    if (this.isUserTown) {
      this.params['service_id.eq'] = this.clientId
    } else {
      this.params['recommend_service.eq'] = this.clientId
      this.params['gua_type.eq'] = 1
    }
    this.getData()
  },
  methods: {
    request() {
      if (this.selectData.length < 1) {
        return this.$message.warning('请先选择项目！')
      }
      this.prelimVisiable = true
    },
    async getData(index = 1) {
      this.params.index = index
      const params = { ...this.params }
      if (!this.isManager && status !== 0) {
        params['pre_approval_person.eq'] = this.userId
      }

      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, {
          create_time: 'desc',
        })
      )
      this.loading = false

      const data = (res && res.data) || {}
      this.totalCount = data.totalCount
      this.tableData = (data.data || []).map(item => {
        item.statusLabel = enumPreApproval[item.is_approval] || '-'
        item.statusStyle = enumStatusStyle[item.is_approval] || ''
        return item
      })
    },
    handleSelectionChange(select) {
      this.selectData = select
    },
    setBank(v, n) {
      this.form.public_bank_ids = v.join('|')
      this.form.public_bank_names = n.join('|')
    },
    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.publicProject()
        } else {
          return false
        }
      })
    },
    async publicProject() {
      this.approvalLoading = true
      let data = {}
      for (let p of this.selectData) {
        data = {
          public_bank_ids: this.form.public_bank_ids,
          public_bank_names: this.form.public_bank_names,
          res_a: this.form.res_a,
          res_b: this.form.res_b,
          gua_type: this.form.gua_type,
          is_approval: 1,
          approval_person: this.userId,
          pre_approval_person: this.userId,
          pre_approval_date: this.$utils.dateFormat(new Date()),
          task_status: 1,
        }
        let [, err] = await this.$utils.promise(
          this.$api.updateData(this.$serviceName, 'customer_related', p.customer_related_id, data)
        )
        if (err) {
          this.approvalLoading = false
          this.$message.error('审核失败，请重试')
          return
        }
      }
      this.$store.dispatch('getTaskCountTown')
      this.$emit('success', true)
      this.$message.success('审核成功！')
      this.getData()
      this.prelimVisiable = false
      this.approvalLoading = false
    },
    beforeClose() {
      this.form.publicBank = []
      this.form.public_bank_ids = ''
      this.form.public_bank_names = ''
      this.prelimVisiable = false
    },
  },
}
</script>

<style scoped></style>
